import ConfigParser
from sc_engine.messaging import ApplicationMessageBus
from sc_engine.messaging import MainMessageBus

def get_transport_from_config(config):
    method = config['transport_method']

    if method == 'amqp':
        from sc_engine.messaging.transports.amqp import AMQPTransport
        
        host = config['amqp_host']
        vhost = config['amqp_vhost']
        return AMQPTransport(host, vhost)
    elif method == 'local':
        from sc_engine.messaging.transports.local import LocalTransport
        return LocalTransport()
    else:
        raise SystemExitError('No known transport method %s' % method)

def parse_config(config_filename):
    config_parser = ConfigParser.SafeConfigParser()
    config_parser.read(config_filename)

    configs = {}
    for section in config_parser.sections():
        configs[section] = dict(config_parser.items(section))

    return configs

    
def run_as_script(script_name, script_run, config_filename):
    config = parse_config(config_filename)
    transport = get_transport_from_config(config['root'])
    bus = MainMessageBus(script_name, transport)
    script_run(bus)
    bus.close()
